/**
 * Created by shenhai on 15/9/25.
 */


angular.module('mis.topicManager.controllers', [])
    .controller('topicManagerCtrl', ['$scope','$http', '$location', function ($scope, $http, $location) {


        $scope.currentPage = 1;
        $scope.pageSize = 15;

        //分页
        $scope.pagination = new pagination({currentPage:$scope.currentPage,pageSize: $scope.pageSize,
            url:'http://' + backOfficeHost + '/rest/v1.0/mis/topic/topicList/:page/:size',
            ajax: $http,
            success:function(data){
                data.data.list.forEach(function(temp) {
                    temp.imageURL = 'http://'+ imgHost+ temp.imageURL;
                });
                $scope.topicList = data.data.list;
                $scope.pageNumber = data.data.totalPage;
                $scope.count = data.data.count;
                $scope.currentPage = $(".am-active").text();
                $scope.pagination.totalPage = data.data.totalPage;
                $scope.pagination.pageHeader($scope.pageNumber);
                $('#count').text("共"+$scope.pageNumber+"页 有"+$scope.count+"数据");
            },
            error: function(err){
                $scope.topicList = null;
            },
            params: {}
        });


        $scope.search = function(current) {

            if (current) {
                $scope.currentPage = $scope.pagination.currentPage;
            }else {
                $scope.pagination.currentPage = 1;
                $scope.currentPage = 1;
            }


            var body = {};
            if ($scope.desc) body.desc = $scope.desc;

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/topic/topicList/' + $scope.currentPage + '/' + $scope.pageSize, body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                data.data.list.forEach(function(temp) {
                    temp.imageURL = 'http://'+ imgHost+ temp.imageURL;
                });
                $scope.topicList = data.data.list;
                $scope.pageNumber = data.data.totalPage;
                $scope.count = data.data.count;

                $scope.pagination.totalPage = data.data.totalPage;
                $scope.pagination.pageHeader($scope.pageNumber);
                $scope.pagination.searchParams = body;

            }).error(function (err) {
                $scope.topicList = null;
            });
        };

        //全选列表
        $scope.allSelected = function(){
            $scope.pagination.allSelected();
        };



        KindEditor.ready(function (K) {
            window.kinAdd = K.create('#editor_id', {
                uploadJson: '/rest/v1.0/Systems/uploadImages'
            });
        });

        KindEditor.ready(function (K) {
            window.kinEdit = K.create('#editor_edit', {
                uploadJson: '/rest/v1.0/Systems/uploadImages'
            });
        });

        $scope.openEdit = function(topic) {

            fileList = {};
            $('#image_result_edit').empty();
            $scope.updateData = topic;
            kinEdit.html("");
            kinEdit.insertHtml(topic.desc);

            $('#doc-modal-edit').modal({target: '#doc-modal-edit',width: 1200, height: 800});

        };

        $scope.clearEditor = function () {
            kinEdit.html('');
        };


        // 选择图片
        //$scope.selectFile = function (files, id) {
        //
        //    if (id == 'icon') $scope.icon = files[0];
        //    //if (id == 'backImg') $scope.backImg = files[0];
        //
        //
        //    var reader = null;
        //    if (FileReader) {
        //        reader = new FileReader();
        //    } else {
        //        alert("浏览器暂时不支持FileReader");
        //    }
        //
        //    reader.readAsDataURL(files[0]);
        //    reader.onload = function () {
        //        $('#'+id).attr("src", reader.result);
        //    };
        //};

        var reader = null;
        if (FileReader) {
            reader = new FileReader();
        } else {
            alert("浏览器暂时不支持FileReader");
        };

        $scope.selectFile = function (files,model) {
            if (model == 'add') {
                document.getElementById("image_result").innerHTML = '';
            }else{
                document.getElementById("image_result_edit").innerHTML = '';
            }
            showImages(model);
        };

        var fileList = {}, length = 0, length1 = 0;
        var showImages = function (model) {

            if(model =='add'){
                var imageEle  = document.getElementById("images_upload");
            }else{
                var imageEle  = document.getElementById("images_upload_edit");
            }

            //获取上传的多个文件
            fileList = imageEle.files;
            length = fileList.length;
            length1 = fileList.length;

            //获取文件信息
            readURL(model);
        };

        var readURL = function (model) {

            reader.readAsDataURL(fileList[length1 - length]);
            reader.onload = function () {
                var img = document.createElement("img");
                img.src = reader.result;
                img.width = 200;
                if(model =='add') {
                    document.getElementById("image_result").appendChild(img);
                }else{
                    document.getElementById("image_result_edit").appendChild(img);
                }
                length--
                if (length == 0)return;
                readURL(model);
            };
        };


        // 发布/编辑 专题
        $scope.handleTopic = function (topic, isEdit, index) {

            if (!topic.title) {alert('请输入标题'); return;}
            if (!topic.summary) {alert('请输入简介'); return;}
            if (!topic.shareDesc) {alert('请输入分享描述'); return;}
            //if (!$scope.backImg && !isEdit) {alert('请选择壁纸'); return;}

            if(isEdit) {
                if (kinEdit.isEmpty()) {alert('请输入内容'); return;}
                var html = kinEdit.html();
            }else{
                if (kinAdd.isEmpty()) {alert('请输入内容'); return;}
                var html = kinAdd.html();
            };

            var a = html.replace(/width=.[0-9]*\"/g, '');
            a = a.replace(/height=.[0-9]*\"/g, '');
            a = a.replace(/\<img/g, '<img style=\"display:block;width:100%;\"');
            a = a.replace(/\<embed/g, '<embed style=\"display:block;width:100%;\"');

            //console.log(topic);

            var temp = new FormData();
            if (isEdit) temp.id = topic.objId; // 编辑
            if (a) temp.desc = a;
            if (topic.title) temp.title = topic.title;
            if (topic.summary) temp.summary = topic.summary;
            if (topic.shareDesc) temp.shareDesc = topic.shareDesc;
            //if ($scope.backImg)  temp.append('image1', $scope.backImg);
            //if ($scope.icon)  temp.append($scope.backImg?'image2':'image1', $scope.icon);
            //if ($scope.icon)  temp.image1 = $scope.icon;
            var fd = new FormData();
            if (fileList != null) {
                for (var i = 0; i < fileList.length; i++) {
                    var index = i + 1;
                    fd.append('image' + index, fileList[i]);
                }
            };

            if (isEdit) {

                if(fileList.length>0){

                    //var fd = new FormData();
                    //fd.append('image1', $scope.icon);
                    //上传图片
                    $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/common/uploadImage', fd, {
                        transformRequest: angular.identity,
                        headers: {'Content-Type': undefined}
                    }).success(function (images) {
                        temp.imageURL = images.data[0];

                        //新数据url有值
                        if (topic.url) {
                            temp.topicId = getQueryString(topic.url, 'topicId');
                        };

                        $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/topic/topicEdit', temp, {
                            headers: {'Content-Type': 'application/json;charset=utf-8'}
                        }).success(function (data) {
                            $('#doc-modal-edit').modal("close");
                            $scope.search(true);
                            alert('更新成功');
                        }).error(function () {
                            $('#doc-modal-edit').modal("close");
                            alert('更新失败');
                        });
                    });
                }else{

                    //新数据url有值
                    if (topic.url) {
                        temp.topicId = getQueryString(topic.url, 'topicId');
                    };

                    $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/topic/topicEdit', temp, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (data) {

                        $('#doc-modal-edit').modal("close");
                        $scope.search(true);
                        alert('更新成功');
                    }).error(function () {
                        $('#doc-modal-edit').modal("close");
                        alert('更新失败');
                    });

                }
            }else {

                if(fileList.length<=0){
                    alert('请选择分享图片!');
                    return;
                }

                //上传图片
                $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/common/uploadImage', fd, {
                    transformRequest: angular.identity,
                    headers: {'Content-Type': undefined}
                }).success(function (images) {
                    temp.imageURL = images.data[0];

                    $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/topic/topicAdd', temp, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (data) {
                        $scope.pagination.selectPage(1);
                        $('#doc-modal-add').modal("close");
                        alert('发布成功');
                    }).error(function () {

                        alert('发布失败');
                    });
                });

            }

        };


        // 预览
        $scope.previewTopic = function (url) {

            $("#code").empty();
            //$("#code").qrcode({
            //    render: "table", //table方式
            //    width: 300, //宽度
            //    height:300, //高度
            //    text: url //任意内容
            //});

            $("#code").qrcode(url)
        };


        // 发布/取消发布
        $scope.handleRelease = function (topic, index, release) {

            var body = {id:topic.objId, isValid:release};

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/topic/topicStatus', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                if (data.result.status == 1) {
                    topic.isValid = release ? true:false;
                }else {
                    alert(release ? '发布失败':'取消发布失败');
                }
            }).error(function (err) {
                alert(release ? '发布失败':'取消发布失败');
            });
        };


        // 删除
        $scope.delete = function(topic,index) {

            if (!topic.objId) return;
            var body = {id:topic.objId};

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/topic/topicDelete', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $('#delete-confirm-'+index).modal("close");
                if (data.result.status == 1) {
                    $scope.search(true);
                }else {
                    alert('删除失败');
                }
            }).error(function (err) {
                alert('删除失败');
            });
        };

    }]);